package com.ta.service.impl;

import com.ta.mapper.AddressMapper;
import com.ta.mapper.CartMapper;
import com.ta.mapper.OrderMapper;
import com.ta.mapper.ProductMapper;
import com.ta.pojo.Address;
import com.ta.pojo.Order;
import com.ta.pojo.OrderItem;
import com.ta.pojo.Product;
import com.ta.pojo.vo.CartVO;
import com.ta.pojo.vo.OrderVO;
import com.ta.service.OrderService;
import com.ta.service.ex.AddressException;
import com.ta.service.ex.OrderException;
import com.ta.util.ThrowServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Timer;

@Service
public class OrderServiceImpl extends ThrowServiceException implements OrderService {
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    
    @Value("${cart.user}")
    private String cartUser;

    /**
     * 实现创建订单业务
     * @param uid
     * @param aid
     * @param cid
     * @param userName
     * @return
     */
    @Override
    public Order insert(Integer uid,
                        Integer aid,
                        Integer[] cid,
                        String userName) {
        Address address = addressMapper.findByAid(aid);
        if (address == null) {
            throw new AddressException("改地址已被删除");
        }
        if (!address.getUid().equals(uid)) {
            throw new AddressException("非法地址访问");
        }

        List<CartVO> cartVOList = cartMapper.findByCids(cid);

        Long totalPrice = 0L;
        for (CartVO cartVO : cartVOList) {
            totalPrice += cartVO.getPrice() * cartVO.getNum();
        }

        Order order = new Order();
        order.setUid(uid);
        order.setRecvName(address.getName());
        order.setRecvPhone(address.getPhone());
        order.setRecvProvince(address.getProvinceName());
        order.setRecvCity(address.getCityName());
        order.setRecvArea(address.getAreaName());
        order.setRecvAddress(address.getAddress());
        order.setTotalPrice(totalPrice);
        order.setStatus(0);
        order.setOrderTime(new Date());
        order.setCreatedUser(userName);
        order.setCreatedTime(new Date());

        Integer row = orderMapper.insertOrder(order);
        if (row != 1) {
            throw new OrderException("创建订单时出现未知异常！");
        }

        /*删除购物车*/
        cartMapper.deleteCids(cid);
        /*同步更新redis缓存*/
        for (Integer id : cid) {
            redisTemplate.opsForHash().delete(cartUser+"_"+uid, id.toString());
        }

        /*关闭订单*/
        /*closeOrder();*/


        for (CartVO cartVO : cartVOList) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOid(order.getOid());
            orderItem.setPid(cartVO.getPid());
            orderItem.setTitle(cartVO.getTitle());
            orderItem.setImage(cartVO.getImage());
            orderItem.setPrice(cartVO.getPrice());
            orderItem.setNum(cartVO.getNum());
            orderItem.setCreatedUser(userName);
            orderItem.setCreatedTime(new Date());

            Integer itemRow = orderMapper.insertOrderItem(orderItem);
            if (itemRow != 1) {
                throw new OrderException("创建订单时出现未知异常！");
            }
        }
        /*保存订单号和总价返回*/
        Order newOrder = new Order();
        newOrder.setOid(order.getOid());
        newOrder.setTotalPrice(totalPrice);

        return newOrder;
    }

    /**
     * 实现订单修改状态业务
     * @param oid
     * @param status
     */
    @Override
    public void modifyStatus(Integer oid, Integer pid,Integer status, String userName) {
        Order order = orderMapper.selectOid(oid);
        if (order.getStatus().equals(2)) {
            throw new OrderException("订单已被取消，请重新下单");
        }

        Integer row = orderMapper.modifyStatus(oid, status, userName, new Date(),new Date());

    }

    /**
     * 实现订单中心业务
     * @param uid
     * @return
     */
    @Override
    public List<OrderVO> selectOrderList(Integer uid) {
        List<OrderVO> orderVOList = orderMapper.selectOrderList(uid);
        return orderVOList;
    }

    /**
     * 实现未收货订单业务
     * @return
     */
    @Override
    public List<OrderVO> selectNoConfirm() {
        return orderMapper.selectNoConfirm();
    }

    /**
     * 实现未付款订单业务
     * @return
     */
    @Override
    public List<OrderVO> selectNoPayment() {
        return orderMapper.selectNoPayment();
    }

    /**
     * 实现未支付订单支付业务
     * @param oid
     * @return
     */
    @Override
    public Order selectOid(Integer oid) {
        return orderMapper.selectOid(oid);
    }

    /**
     * 实现订单详情业务
     * @param oid
     * @return
     */
    @Override
    public OrderVO selectOrderInfo(Integer oid ,Integer uid) {
        OrderVO orderVO = orderMapper.selectOrderInfo(oid);
        if (orderVO == null) {
            throw new OrderException("订单不存在");
        }
        if (!orderVO.getUid().equals(uid)) {
            throw new OrderException("非法数据访问");
        }
        return orderVO;
    }

    @Override
    public Integer paymentOrder(Map<String, Object> map) {
        Integer oid = (Integer)map.get("oid");
        Integer status = (Integer)map.get("status");
        String  userName = (String) map.get("userName");
        orderMapper.modifyStatus(oid, status, userName, new Date(), new Date());
        return 1;
    }

}
